package com.cloud.common.bjy;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.google.common.base.CaseFormat;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 签名工具
 */
public class SignUtils {
    /**
     * 签名
     *
     * @return
     */
    public static String getSign(Map<String, String> map, String partnerKey) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {

                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });

            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (StrUtil.isEmpty(item.getKey())) {
                    continue;
                }
                String key = item.getKey().toLowerCase();
                String value = Convert.toStr(item.getValue());
//                if (key.equals("partner_id") || key.equals("sign")) {
//                    continue;
//                }
                sb.append(key).append("=").append(value).append("&");
            }
            sb.append("partner_key=" + partnerKey);
            //进行MD5加密
            result = DigestUtils.md5Hex(sb.toString()).toLowerCase();
        } catch (Exception e) {
            return null;
        }
        return result;
    }

    /**
     * 签名
     *
     * @return
     */
    public static String sign(Map<String, Object> params, String partnerKey) {
        StringBuilder paramStringBuilder = new StringBuilder(5 * params.size());
        Set<Map.Entry<String, Object>> paramSet = params.entrySet();
        for (Map.Entry<String, Object> entry : paramSet) {
            paramStringBuilder.append(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, entry.getKey())).append("=").append(entry.getValue()).append("&");
        }
        paramStringBuilder.append("partner_key=").append(partnerKey);
        String md5 = DigestUtils.md5Hex(paramStringBuilder.toString());
        return md5.toLowerCase();
    }
}
